package com.zscat.front;


import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.zscat.shop.model.WGoods;
import com.zscat.shop.service.WGoodsService;
import com.zscat.shop.service.WtypeService;

/**
 * 前台 controller
 * @author www.inxedu.com
 */
@Controller
@RequestMapping("front")
public class FrontController  {

	private static final Logger logger = LoggerFactory.getLogger(FrontController.class);
	
	@Resource
	WtypeService WtypeService;
	@Resource
	WGoodsService WGoodsService;

	
	
	/**
	 * 首页获取网站首页数据
	 */
	@RequestMapping("/index")
	public String getIndexpage(HttpServletRequest request, Model model) {
		model.addAttribute("theme_color", "blue");
			model.addAttribute("num", System.currentTimeMillis());
			List<WGoods> list=WGoodsService.selectPage(1, 16, new WGoods(),"clickhit desc").getList();	
			model.addAttribute("teacherList", null);
			model.addAttribute("commentList", null);

			model.addAttribute("list", list);
		return "/index";
	}
	
	@RequestMapping("/detail/{id}")
	public ModelAndView goodsDetail(@PathVariable("id") Long id,HttpServletRequest req)throws Exception{
		ModelAndView mav=new ModelAndView();
		WGoods goods=WGoodsService.selectByPrimaryKey(id);
		mav.addObject("course", goods);
		PageInfo<WGoods> list=WGoodsService.selectPage(1, 16, new WGoods(),"recom");
		mav.addObject("list", list);
		mav.setViewName("detail");
		return mav;
	}
	/**
	 * 首页获取网站首页数据
	 */
	@RequestMapping("/readme")
	public String readme(HttpServletRequest request, Model model) {
		model.addAttribute("theme_color", "blue");
			model.addAttribute("num", System.currentTimeMillis());
			model.addAttribute("teacherList", null);
			model.addAttribute("commentList", null);
		return "/readme";
	}
	
	// 首页精品课程、最新课程、全部课程
		@RequestMapping("/ajax/bna")
		public String queryCourse(HttpServletRequest request) {
			try {
				String order = request.getParameter("order");
				if (order != null && !order.equals("")) {
					List<WGoods> list=null;
					if("HIT".equals(order)){
						list=WGoodsService.selectPage(1, 16, new WGoods(),"clickhit desc").getList();	
					}else if("NEW".equals(order)){
						list=WGoodsService.selectPage(1, 16, new WGoods(),"addTime desc").getList();
					}else if("ALL".equals(order)){
						list=WGoodsService.selectPage(1, 16, new WGoods(),"addTime desc").getList();
					}
					request.setAttribute("list", list);

				}
			} catch (Exception e) {
				logger.error("WebFrontController.queryCourse", e);
				e.printStackTrace();
			}
			return "/ajax-course-bna";
		}
		
	// 首页为你推荐换一换功能(随机获取)
	@RequestMapping("/ajax/huanyihuan")
	public String queryRecommenCourseListByRecommendId(HttpServletRequest request) {
		try {
			// RecommendId是分类Id
			// 获得为你推荐的课程
			//List<EduCourse> courseDtoList = EduCourseService.queryRecommenCourseListByRecommendId(2l, 4l);
//			EduCourse eduCourse=new EduCourse();
//			List<EduCourse> courseDtoList = EduCourseService.select(eduCourse);
//			request.setAttribute("courseDtoList", courseDtoList);
		} catch (Exception e) {
			logger.error("WebFrontController.queryRecommenCourseListByRecommendId", e);
			e.printStackTrace();
		}
		return "/front/edu/ajax-course-recommend";
	}

	// 首页学生动态
	@RequestMapping("/index/ajax/studentDynamic")
	public String studentDynamic(HttpServletRequest request) {
		try {
			//课程学习记录
//			 List<CourseStudyhistory> courseStudyhistoryList = (List<CourseStudyhistory>) EHCacheUtil.get(CacheConstans.INDEX_STUDENT_DYNAMIC);
//				if(ObjectUtils.isNull(courseStudyhistoryList)){
//					CourseStudyhistory courseStudyhistory=new CourseStudyhistory();
//					courseStudyhistory.setQueryLimit(4);//限制4条
//					courseStudyhistoryList=EduCourseStudyhistoryService.getCourseStudyhistoryList(courseStudyhistory);
//					
//				}
//				EduCourseStudyhistory courseStudyhistory=new EduCourseStudyhistory();
//				
//				List<EduCourseStudyhistory>	courseStudyhistoryList=EduCourseStudyhistoryService.select(courseStudyhistory);
//			request.setAttribute("courseStudyhistoryList", courseStudyhistoryList);
		} catch (Exception e) {
			logger.error("studentDynamic", e);
			e.printStackTrace();
		}
		return "/front/edu/ajax-student-dynamic";//页面
	}
		
	
	/**
	 * 跳转找回密码页面
	 */
	@RequestMapping("/front/passwordRecovery")
	public ModelAndView passWordRecovery(){
		return new ModelAndView("/web/user/password-recovery");
	}
	
	/** 
	 * 修改主题色
	 * 
	 */
//    @RequestMapping("/theme/ajax/update")
//    @ResponseBody
//    public Object updateTheme(HttpServletRequest request,@RequestParam String color) {
//    	Map<String,Object> json = new HashMap<String,Object>();
//		changeColor(request,color);
//		json = this.setJson(true, color, "");
//		return json;
//    }
//    
//    public void changeColor(HttpServletRequest request,String colorfalg){
//    	String color="#ea562e";
//    	if (colorfalg.equals("blue")) {
//    		color="#009ed9";
//		}else if (colorfalg.equals("green")) {
//    		color="#68cb9b";
//		}
//    	
//    	//放入缓存
//    	EHCacheUtil.set("inxedu_index_theme_color",colorfalg,21600);//缓存六小时
//    	//获得项目根目录
//    	String strDirPath = request.getSession().getServletContext().getRealPath("/");     	
//    	//读取字符串
//    	StringBuffer sb = new StringBuffer();
//    	//当前读取行数
//    	int rowcount = 1 ;
//    	//要修改的行数
//    	int updaterowcount = 2 ;
//    	FileReader fr;
//    	try {
//			String path = strDirPath+"/static/inxweb/css/less/theme.less";
//			fr = new FileReader(path);
//			BufferedReader br = new BufferedReader(fr);
//			String line = br.readLine();
//			while (line != null) {
//				if(rowcount==updaterowcount&&StringUtils.isNotEmpty(color)){
//					sb.append("@mColor:"+color+";");
//				}else{
//					sb.append(line);
//				}
//				line = br.readLine();
//				rowcount++;
//			}
//			br.close();
//			fr.close();
//			LessEngine engine = new LessEngine();
//			FileWriter fw = new FileWriter(strDirPath+"/static/inxweb/css/theme.css");
//		    fw.write(engine.compile(sb.toString()));
//			fw.flush();
//			fw.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//			
//		}
//    }
    
    /** 
	 * 根据用户key 获得登录用户（用于小组登录）
	 * 
	 */
//    @RequestMapping("/user/ajax/logined")
//    @ResponseBody
//    public Object getLoginUserByKey(HttpServletRequest request,@RequestParam String userKey) {
//    	Map<String,Object> json = new HashMap<String,Object>();
//    	User user = (User) EHCacheUtil.get(userKey);
//		//User user = (User) request.getSession().getAttribute(userKey);
//		if(ObjectUtils.isNotNull(user)){
//			//添加需要的属性
//			WebLoginUser webLoginUser=new WebLoginUser();
//			webLoginUser.setId(Long.valueOf(user.getUserId()));
//			webLoginUser.setCusId(Long.valueOf(user.getUserId()));
//			webLoginUser.setEmail(user.getEmail());
//			webLoginUser.setGender(user.getSex());
//			webLoginUser.setId(Long.valueOf(user.getUserId()));
//			webLoginUser.setMobile(user.getMobile());
//			webLoginUser.setNickname(user.getShowName());
//			webLoginUser.setRealname(user.getUserName());
//			webLoginUser.setAvatar(user.getPicImg());
//			webLoginUser.setUserInfo("这个人很懒，他还没有签名");
//			
//			JsonParser jsonParser = new JsonParser();
//	        JsonObject jsonObject  = jsonParser.parse(new Gson().toJson(webLoginUser)).getAsJsonObject();
//			json = this.setJson(true, "", jsonObject.toString());
//		}else{
//			json = this.setJson(false, "", "");
//		}
//		
//		return json;
//    }

	/**
	 * 帮助中心
	 *
	 * @param request
	 * @param model
	 * @return
	 */
//	@RequestMapping("/front/helpCenter")
//	public String getHelpCenter(HttpServletRequest request, Model model) {
//		try {
//			// 右侧显示内容的二级菜单id
//			String id = request.getParameter("id");
//			// 帮助中心菜单集合，不含内容
//			List<List<HelpMenu>> helpMenus = helpMenuService.getHelpMenuAll();
//			model.addAttribute("helpMenus", helpMenus);
//
//			// 右侧显示内容
//			HelpMenu helpMenuContent = null;
//			if (id != null && !id.equals("")) {
//				helpMenuContent = helpMenuService.getHelpMenuById(Long.parseLong(id));
//			} else if (helpMenus.size() > 0 && helpMenus.get(0).get(1) != null) {
//				helpMenuContent = helpMenuService.getHelpMenuById(helpMenus.get(0).get(1).getId());
//			}
//			model.addAttribute("helpMenuContent", helpMenuContent);//显示的
//
//		} catch (Exception e) {
//			logger.error("WebFrontController.getHelpCenter", e);
//			return setExceptionRequest(request, e);
//		}
//		return getViewPath("/web/front/helpCenter");
//	}
}
